package nico.styTool.service

import android.annotation.SuppressLint
import android.app.Dialog
import android.content.Context
import android.os.Build
import android.view.*
import androidx.core.content.ContextCompat
import cn.vove7.andro_accessibility_api.AccessibilityApi
import cn.vove7.andro_accessibility_api.api.lockScreen
import cn.vove7.andro_accessibility_api.api.screenShot
import cn.vove7.andro_accessibility_api.api.splitScreen
import cn.vove7.andro_accessibility_api.api.withId
import cn.vove7.andro_accessibility_api.ext.ScreenTextFinder
import cn.vove7.andro_accessibility_api.viewfinder.ViewFindBuilder
import com.blankj.utilcode.util.ResourceUtils
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ScreenUtils.getAppScreenHeight
import com.blankj.utilcode.util.ScreenUtils.getAppScreenWidth
import com.blankj.utilcode.util.ToastUtils
import com.blankj.utilcode.util.UtilsTransActivity4MainProcess
import com.drake.engine.utils.DeviceUtils.*
import com.example.blade.Constant
import com.example.blade.ReaderUtil
import com.example.blade.ReaderUtil.jExit
import com.example.blade.util.accessibility.PerformClickUtils
import com.example.blade.util.accessibility.ToolsService
import com.lzf.easyfloat.EasyFloat
import com.lzf.easyfloat.enums.ShowPattern
import kotlinx.android.synthetic.main.float_tail.view.*
import kotlinx.android.synthetic.main.layout_custom.view.*
import nico.styTool.R
import java.util.*


@Suppress("NonAsciiCharacters")
class BasicService(int: Int, context: Context) {

    private val context0 by lazy { context }
    private val accessibilityApi = ToolsService()._baseService

    init {
        when (int) {
            0 -> QQ名片自动回赞()
            1 -> QQ消息扣字器()
            2 -> QQ删除历史名片赞()
            3 -> 分析布局()
            4 -> 聊天输入小尾巴()
            5 -> 一键锁屏()
            6 -> 一键分屏()
            7 -> 一键截屏()
            8 -> shutdown()
            9 -> reboot()
            10 -> reboot2Recovery()
            11 -> reboot2Bootloader()
            else -> {
            }
        }
    }

    private fun 一键截屏() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            EasyFloat.with(context0).setLayout(R.layout.float_tail) { view ->
                view.also {
                    it.setOnClickListener { screenShot() }
                    val drawable =
                        ContextCompat.getDrawable(context0, R.drawable.ic_twotone_camera_24)
                    it.imageView3.setImageDrawable(drawable)
                }
            }.setTag("一键截屏")/*.setFilter(UtilsTransActivity4MainProcess::class.java)*/
                .setShowPattern(ShowPattern.ALL_TIME).show()
        } else {
            ToastUtils.showShort("系统需求Android P(9)")
            //jExit(accessibilityApi as AccessibilityApi, false)
        }
    }

    private fun 一键分屏() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            splitScreen()
        } else {
            nico.styTool.Utils.setToast("系统不兼容该功能!")
        }
    }

    private fun 一键锁屏() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            lockScreen()
        } else {
            nico.styTool.Utils.setToast("系统不兼容该功能!")
        }
    }

    private fun 聊天输入小尾巴() {
        val key = "switch_preference_1_Burst"
        val branch = SPUtils.getInstance(Constant.spName).getBoolean(key, true)
        val sp = SPUtils.getInstance(Constant.spName).getString("edit_text_preference_1_tail")
        EasyFloat.with(context0).setLayout(R.layout.float_tail) { view ->
            view.also {
                it.setOnClickListener {
                    ViewFindBuilder().invoke {
                        try {
                            editable().appendText(if (branch) "\n${sp}" else sp)
                        } catch (e: Exception) {
                            ToastUtils.showShort("这个页面没输入框？\n${e.message}")
                        }
                    }
                }
            }
        }.setTag("聊天输入小尾巴").setFilter(UtilsTransActivity4MainProcess::class.java)
            .setShowPattern(ShowPattern.ALL_TIME).show()
    }

    @SuppressLint("InflateParams")
    private fun 分析布局() {
        LayoutInflater.from(context0).inflate(R.layout.layout_custom, null).apply {
            val view = this
            val dialog = Dialog(context0/*, R.style.theme_transparent*/)
            if (dialog.window != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                    dialog.window!!.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
                } else {
                    dialog.window!!.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
                }
            }
            dialog.setContentView(this, ViewGroup.LayoutParams(AppWidth, AppHeight))
            dialog.create()
            dialog.show()
            ScreenTextFinder().find().joinToString("\n\n").apply {
                view.textView3.text = this
            }
        }
    }

    private fun QQ消息扣字器() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            repeat(100) {
                val ran = System.currentTimeMillis()
                val txt = pass[Random(ran).nextInt(pass.size)]
                val sp = SPUtils.getInstance(Constant.spName)
                    .getBoolean("switch_preference_1_Burst", false)
                val spTxt =
                    SPUtils.getInstance(Constant.spName)
                        .getString("edit_text_preference_1_Burst", " ")
                try {
                    withId("input").editable().trySetText(if (sp) txt else spTxt)
                    withId("fun_btn").tryClick()
                } catch (e: Exception) {
                }
            }
        } else {
            ToastUtils.showShort("android 7（N）以下不支持该功能，请换设备")
        }
    }

    private fun QQ名片自动回赞() {
        repeat(250) {
            ViewFindBuilder().invoke {
                try {
                    id("dyw").tryClick()
                } catch (e: Exception) {
                }
            }
        }
    }

    private fun QQ删除历史名片赞() {
        val id2 = "com.tencent.mobileqq:id/ajn"
        val lvs = accessibilityApi.rootInActiveWindow.findAccessibilityNodeInfosByViewId(id2)
        if (lvs != null) {
            if (lvs.size != 0) {
                repeat(10) {
                    PerformClickUtils.findViewIdAndClick(accessibilityApi, id2)
                }
                ToastUtils.showShort("请下拉刷新")
            }
        }
    }

    companion object {
        private val AppWidth = getAppScreenWidth()
        private val AppHeight = getAppScreenHeight()
        private val pass = ResourceUtils.readAssets2List("nb.txt")
    }
}